var cgi_moduleId = RequestURLParam.getParam("moduleId") || ''
    , fid = RequestURLParam.getParam("fid") || ''
    , activeFlag = RequestURLParam.getParam("activeFlag") || ''
    , cgi_moduleName = decodeURIComponent(RequestURLParam.getParam("moduleName") || '')
    , urlTxt = "/wf/workflow/addNewWorkFlow"
    , frameId = window.frameElement && window.frameElement.id || ''
    , form,
    layer;
//判断是否为添加或者修改
$(document).ready(function () {
    init_layui();
    if (fid) {
        urlTxt = "/wf/workflow/update";
        init_data();
    } else {
        $('#moduleId').val(cgi_moduleId);
        $('#moduleDisplayName').text(cgi_moduleName);
        $('#orderNum').val(0);
    }
    showStatus(activeFlag);
});

function init_layui() {
    layui.use(['jquery', 'form', 'layer'], function () {
        $ = layui.jquery
            , form = layui.form
            , layer = layui.layer;
        form.on("submit(saveData)", function (data) {
            if ($("#wfTitle1").val() === "" && $("#wfTitle2").val() === "") {
                layer.msg("请填写标题", {icon: 2, time: 1000});
                return;
            }
            //表单提交
            var formData = data.field;
            var sta = $("#activeFlag").text();
            if (sta == '启用') {
                formData['activeFlag'] = 1;
            } else if (sta == '关闭中') {
                formData['activeFlag'] = 2;
            } else {
                formData['activeFlag'] = 3;
            }
            //处理标题
            var firstTitle = $("#wfTitle1").val(),
                secondTitle = $("#wfTitle2").val(),
                title = "{{" + $("#title option:selected").val() + "}}";
            if (firstTitle) {
                title = firstTitle + title;
            }
            if (secondTitle) {
                title += secondTitle;
            }
            formData['wfTitle'] = title;
            ActHttpRequest(urlTxt, formData, function (data) {
                if (data.OK === "OK") {
                    parent.layer.msg("操作成功!", {icon: 1});
                    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                    parent.layer.close(index); //再执行关闭
                } else {
                    layer.alert(data.message);
                }
            });
            return false;
        });

        $(document).on('click', '.emptyThis', function () {
            $(this).siblings(".formEditName").val("");
            var thisId = $(this).siblings(".formEditName").attr("lableId");
            $("#" + thisId).val("");
        });
        //选择表单
        $(document).on("mousedown", "#formEditName", function () {
            parent.layer.open({
                type: 2
                ,
                title: '选择表单'
                ,
                content: '/base/workFlow/workFlow/formSelector.html?name=formEditName&frameId=' + frameId + "&moduleId=" + cgi_moduleId
                ,
                area: ['1000px', '600px'],
                cancel: function () {

                }
            });
        });

        //打印表单
        $(document).on("mousedown", "#formPrintName", function () {
            parent.layer.open({
                type: 2
                ,
                title: '选择表单'
                ,
                content: '/base/workFlow/workFlow/formSelector.html?name=formPrintName&frameId=' + frameId + "&moduleId=" + cgi_moduleId
                ,
                area: ['1000px', '600px'],
                cancel: function () {

                }
            });
        })
        load_title("");
    });
}

/*
* @author: wj
* @description: 加载标题配置选项
* @date: 2019/3/13 9:23
* @param
* @return
*/
function load_title(wftitle) {

    layui.use('form', function () {
        var form = layui.form,
            firstTitle = "",
            secondTitle = "",
            title = "";
        if (wftitle) {
            var reg = new RegExp('^.*}}$');
            if (wftitle.indexOf("{{") == 0) {
                var index = wftitle.indexOf("}}");
                secondTitle = wftitle.substring(index + 2);
                title = wftitle.substring(0, index + 1);
            } else if (reg.test(wftitle)) {
                var index = wftitle.indexOf("{{");
                firstTitle = wftitle.substring(0, index);
                title = wftitle.substring(index);
            } else {
                var index_1 = wftitle.indexOf("{{"),
                    index_2 = wftitle.indexOf("}}");
                firstTitle = wftitle.substring(0, index_1);
                secondTitle = wftitle.substring(index_2 + 2, wftitle.length);
                title = wftitle.substring(index_1 + 2, index_2)
            }
            $("#wfTitle1").val(firstTitle);
            $("#wfTitle2").val(secondTitle);
        }
        ActHttpRequest("/wf/workflow/getWfForm", {'wfId': fid}, function (d) {
            var $html = "";
            if (d.formField) {
                $.each(d.formField, function (index, item) {
                    if (item != null) {
                        if (title === item.name) {
                            $html += '<option value="' + item.name + '" selected>' + item.displayName + '</option>'
                        } else {
                            $html += "<option value='" + item.name + "'>" + item.displayName + "</option>";
                        }
                    }
                });

                $("select[name='wftitle']").empty();
                $("select[name='wftitle']").append($html);
                //append后必须从新渲染
                form.render('select');
            }
        });
    });
}

//显示状态
function showStatus(activeFlag) {
    if (activeFlag === '1') {
        $("#activeFlag").text('启用');
        $("#onOrOff").text('状态关闭');
    } else if (activeFlag === '2') {
        $("#activeFlag").text('关闭中');
        $("#onOrOff").text('状态启用');
    } else {
        $("#activeFlag").text('已关闭');
        $("#onOrOff").text('状态启用');
    }
}

//改变状态
function changeState() {
    if ($("#activeFlag").text() == '启用') {
        updateActiveFlag();
    } else {
        $("#activeFlag").text('启用');
        $("#activeFlag").val(1);
        $("#onOrOff").text('状态关闭');
    }
}

/*
* @author: wj
* @description: 状态启用
* @date: 2019/3/4 10:49
* @param
* @return
*/
function updateActiveFlag() {
    ActHttpRequest("/wf/workflow/getWorkFlowState", {"id": fid}, function (data) {
        if (data.OK === 'OK') {
            if (data.flag === true) {
                $("#activeFlag").text('已关闭');
                $("#onOrOff").text('状态启用');
            } else {
                $("#activeFlag").text('关闭中');
                $("#onOrOff").text('状态启用');
            }
        } else {
            layer.msg('操作失败！', {
                icon: 1,
                time: 1000 //2秒关闭（如果不配置，默认是3秒）
            })
        }
    }, null, null, null, '加载中。。。');

}

//初始化
function init_data() {
    ActHttpRequest("/wf/workflow/" + fid, {}, function (data) {
        if (!data) {
            return;
        }
        if (!data.wfWorkflow) {
            return;
        }
        $("#mainform .wfWorkflow").each(function () {
            $('#' + this.id).val(data.wfWorkflow[this.id])
        });
        load_title(data.wfWorkflow.wfTitle);
    }, 'post', null, null, '加载中。。。');
}

/*
* @author: wj
* @description: 选择表单回调
* @date: 2019/3/9 14:12
* @param
* @return
*/
function changeSelectedValue(data) {
    var formId = data.formId;
    var formName = data.formName;
    load_titles(formId);
    if (data.name === "formEditName") {
        $("#formEditId").val(formId);
    } else if (data.name === "formViewName") {
        $("#formViewId").val(formId);
    } else {
        $("#formPrintId").val(formId);
    }
    $('#' + data.name).val(formName);
}

function load_titles(formId) {
    ActHttpRequest("/wf/workflow/getWfFormByFormId", {'id': formId}, function (d) {
        var $html = "";
        if (d.formField) {
            $.each(d.formField, function (index, item) {
                if (item != null) {
                    if (title === item.name) {
                        $html += '<option value="' + item.name + '" selected>' + item.displayName + '</option>'
                    } else {
                        $html += "<option value='" + item.name + "'>" + item.displayName + "</option>";
                    }
                }
            });

            $("select[name='wftitle']").empty();
            $("select[name='wftitle']").append($html);
            //append后必须从新渲染
            form.render('select');
        }
    });
}